using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Roles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.Roles.CommandHandlers;

public class CreateRoleCommandHandler : IRequestHandler<CreateRoleCommand, Result>
{
    private readonly IRoleService _roleService;

    public CreateRoleCommandHandler(IRoleService roleService)
    {
        _roleService = roleService;
    }
    public async Task<Result> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
    {
        var isExistRole = await _roleService.RoleExistsByNameAsync(request.roleName);
        if (isExistRole) return Result.Failure("角色已存在");

        var role = Role.CreateRole(request.roleCode, request.roleName,request.description,request.status);

        var result = await _roleService.CreateRoleAsync(role.Id,role.Code, role.Name,role.Description,role.Status);

        if (!result.Succeeded) return Result.Failure(result.Errors);

        return Result.Success();
    }
}